import { useState, useCallback, useEffect } from 'react';
import app from '@/services/ws/event';

export default () => {
  // @ts-ignore
  const defaultLength = 200;
  const [websocketData, setWebsocketData] = useState<any[]>([]);
  const pushData = useCallback((item: any) => {
    setWebsocketData((prevState) => [...prevState, item]);
    if (websocketData.length > defaultLength) {
      const length = websocketData.length - defaultLength;
      const list = websocketData.slice(length);
      setWebsocketData([...list]);
    }
  }, []);
  const clearData = useCallback((item: any) => {
    setWebsocketData([]);
  }, []);
  useEffect(() => {
    //@ts-ignore
    app.register('onlog', (data) => {
      pushData(data);
    });
  }, []);

  return { websocketData, pushData, clearData };
};
